//
//  JHBookDataListView.m
//  JuniRengLish_iOS
//
//  Created by Maiyou on 2019/5/16.
//  Copyright © 2019 revogi. All rights reserved.
//

#import "JHBookDataListView.h"

static NSString * const cellID = @"JHMiddleWordDownloadCell";

@implementation JHBookDataListView

- (instancetype)initWithFrame:(CGRect)frame
{
    if ([super initWithFrame:frame])
    {
        self.frame = frame;
    }
    return self;
}

#pragma mark - 懒加载
- (JHBookDownLoadView *)headerView
{
    if (!_headerView)
    {
        WEAKSELF
        _headerView = [[[NSBundle mainBundle]loadNibNamed:@"JHBookDownLoadView" owner:self options:nil]lastObject];
        _headerView.currentVC = self.currentVC;
        _headerView.isBook = self.isBook;
        _headerView.bookDetailModel = self.bookDetailModel;
        _headerView.backgroundColor = JKGlobalBgColor;
        _headerView.downLoadBtnBlock = ^(BOOL status) {
            weakSelf.isDowning = status;
            [weakSelf.tableView reloadData];
        };
    }
    return _headerView;
}

- (void)setRequestUrl:(NSString *)requestUrl
{
    _requestUrl = requestUrl;
    
    [self requestData];
    
    //删除单词的所有下载文件
    if (self.isBook)
    {
        [kNotificationCenter addObserver:self selector:@selector(deleteUnitAllData:) name:@"deleteBookUnitAllData" object:nil];
    }
    else
    {
        [kNotificationCenter addObserver:self selector:@selector(deleteUnitAllData:) name:@"deleteWordUnitAllData" object:nil];
    }
}

- (void)requestData
{
    [DJHttpTool getWithURL:self.requestUrl params:nil success:^(id json) {
        self.bookDetailModel = [JHBookDetailModel mj_objectWithKeyValues:json];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
    }];
}

- (UITableView *)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc] initWithFrame:self.bounds style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 50;
        [_tableView registerNib:[UINib nibWithNibName:@"JHMiddleWordDownloadCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:cellID];
        [self addSubview:_tableView];
    }
    return _tableView;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.isBook)
    {
        return self.bookDetailModel.bookitem.count;
    }
    return self.bookDetailModel.worditem.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return [self.headerView isAllBookExistFile] ? 0.001 : 80;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.001;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    return [self.headerView isAllBookExistFile] ? [UIView new] : self.headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JHMiddleWordDownloadCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    cell.bookid = self.bookDetailModel.bookinfo.bookid;
    cell.txtdownloadurl = self.bookDetailModel.bookinfo.txtdownloadurl;
    cell.isBook = self.isBook;
    if (self.isBook)
    {
        JHBookItemModel *model = self.bookDetailModel.bookitem[indexPath.row];
        cell.itemModel = model;
        cell.nameLable.text = model.unitname;
    }
    else
    {
        JHWordItemModel *model = self.bookDetailModel.worditem[indexPath.row];
        cell.wordItemModel = model;
        cell.nameLable.text = model.unitname;
    }
    cell.currentVC = self.currentVC;
    cell.downLoadCompleteBlock = ^(BOOL status) {
        self.isDowning = status;
        [self.tableView reloadData];
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isDowning)
    {
        [DJToast showBottomToast:@"正在下载，请等待下载"];
    }
    else
    {
        JHMiddleWordDownloadCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        [cell selectDownLoadAndPlayVoice];
    }
}

- (void)deleteUnitAllData:(NSNotification *)noti
{
    if ([noti.object isEqualToString:@"word"])
    {
        [self.currentVC jxt_showAlertWithTitle:@"温馨提示" message:@"是否删除文件？" appearanceProcess:^(JXTAlertController * _Nonnull alertMaker) {
            alertMaker.addActionCancelTitle(@"取消").addActionDefaultTitle(@"确定");
        } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, JXTAlertController * _Nonnull alertSelf) {
            if (buttonIndex == 1) {
                for (int i = 0; i < self.bookDetailModel.worditem.count; i ++)
                {
                    JHWordItemModel * model = self.bookDetailModel.worditem[i];
                    for (int j = 0; j < model.data.count; j ++)
                    {
                        JHWordItemDataModeel * dataModel = model.data[j];
                        NSString * mp3Path = [NSString stringWithFormat:@"%@/%@/%@.mp3", [JHFileManger getDocumentsPath], self.bookDetailModel.bookinfo.bookid, dataModel.mp3name];
                        if ([JHFileManger fileExistsAtPath:mp3Path])
                        {
                            [JHFileManger removeItemAtPath:mp3Path];
                        }
                        NSString * textPath = [NSString stringWithFormat:@"%@/%@/%@", [JHFileManger getDocumentsPath], self.bookDetailModel.bookinfo.bookid, dataModel.textfile];
                        if ([JHFileManger fileExistsAtPath:mp3Path])
                        {
                            [JHFileManger removeItemAtPath:textPath];
                        }
                    }
                }
                [DJToast showCenterToast:@"删除完成"];
                [self.tableView reloadData];
            }
        }];
    }
    else if ([noti.object isEqualToString:@"book"])
    {
        [self.currentVC jxt_showAlertWithTitle:@"温馨提示" message:@"是否删除文件？" appearanceProcess:^(JXTAlertController * _Nonnull alertMaker) {
            alertMaker.
            addActionCancelTitle(@"取消").
            addActionDefaultTitle(@"确定");
        } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, JXTAlertController * _Nonnull alertSelf) {
            if (buttonIndex == 1) {
                for (int i = 0; i < self.bookDetailModel.bookitem.count; i ++)
                {
                    JHBookItemModel * model = self.bookDetailModel.bookitem[i];
                    for (int j = 0; j < model.data.count; j ++)
                    {
                        JHBookItemDataModel * dataModel = model.data[j];
                        NSString * mp3Path = [NSString stringWithFormat:@"%@/%@/%@.mp3", [JHFileManger getDocumentsPath], self.bookDetailModel.bookinfo.bookid, dataModel.mp3name];
                        if ([JHFileManger fileExistsAtPath:mp3Path])
                        {
                            [JHFileManger removeItemAtPath:mp3Path];
                        }
                        NSString * textPath = [NSString stringWithFormat:@"%@/%@/%@", [JHFileManger getDocumentsPath], self.bookDetailModel.bookinfo.bookid, dataModel.textfile];
                        if ([JHFileManger fileExistsAtPath:mp3Path])
                        {
                            [JHFileManger removeItemAtPath:textPath];
                        }
                    }
                }
                [DJToast showCenterToast:@"删除完成"];
                [self.tableView reloadData];
            }
        }];
    }
}

@end
